import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Router} from '@angular/router';
import {UserService} from '../service/user.service';
import {Catalog} from '../../post/model/catalog';
import {Message} from 'primeng/components/common/api';

@Component({
  selector: 'app-userspace',
  templateUrl: './userspace.component.html',
  styleUrls: ['./userspace.component.css']
})
export class UserspaceComponent implements OnInit {
  catalogs:Catalog[]=null;
  catalog:Catalog=new Catalog();
  display:boolean = false;
  msgs: Message[] = [];
  constructor(public http:HttpClient,public router:Router,public userService:UserService) { }

  ngOnInit() {
    this.http.get('/catalogs').subscribe(result=>{
      if(result['error']=="未登录"){
        this.userService.currentUser=null;
        this.router.navigateByUrl("/user/login");
      }else{
        this.catalogs = result['data'];
      }
    });
  }


  showEditCatalogDialog(catalog:Catalog){
    if(catalog==null){
      this.catalog = new Catalog();
    }else{
      //不能直接写成this.catalog=catalog,this.catalog和catalog会是一个对象
      this.catalog = new Catalog();
      this.catalog.id=catalog.id;
      this.catalog.name=catalog.name;
      this.catalog.user=catalog.user;
    }

    this.display=true;
  }
  editCatalog(){
    if(this.catalog.name==''){
      this.msgs = [];
      this.msgs.push({severity: 'error', summary: '分类名称不能为空'});
      return;
    }else{
      this.http.post("/catalog",this.catalog).subscribe(result=>{
        if(result['error']=="未登录"){
          this.router.navigateByUrl("/user/login");
        }else{
          this.ngOnInit();
        }
      })
    }
    this.display=false;
  }
  deleteCatalog(catalog:Catalog) {
    this.http.delete('/catalog?id='+catalog.id).subscribe(data=>{
      this.ngOnInit();
    });
  }


}
